<template>
  <div class="form-user">
    <template v-if="isOpenData && staffIds && staffIds.length">
      <div v-if="!canDelete" class="open-data-input" @click="choose">
        <open-data v-for="staffId in staffIds" :key="staffId" type="userName" :openid="staffId"></open-data>
      </div>
      <div v-else class="open-data-input flex-x flex-w" @click="choose">
        <template v-if="collapseTags">
          <div v-show="value && value.length > 0"  class="flex-x open-data-item">
            <div class="open-data-item-con"><open-data  type="userName" :openid="value[0].staffId"></open-data></div> <i @click.stop="deleteItem(value[0])" class="el-tag__close el-icon-close"></i>
          </div>
          <div class="flex-x open-data-item" v-show="value && value.length > 1">
            +{{value.length - 1}}
          </div>
        </template>
        <template v-else>
          <div v-for="item in value" :key="item.id" class="flex-x open-data-item">
            <div class="open-data-item-con"><open-data  type="userName" :openid="item.staffId"></open-data></div> <i @click.stop="deleteItem(item)" class="el-tag__close el-icon-close"></i>
          </div>
        </template>
      </div>
    </template>
    <template v-else>
      <input 
        :id="`form_${field.fieldName}`" 
        :value="displayName"
        :placeholder="placeholder"
        readonly 
        v-if="!canDelete"
        :disabled="disabled"
        @click="choose"
      >
      <div v-else class="open-data-input flex-x flex-w" @click="choose">
        
         <template v-if="collapseTags">
            <div v-show="value && value.length > 0"  class="flex-x open-data-item">
              <div class="open-data-item-con">{{value[0] && value[0].displayName}}</div> <i @click.stop="deleteItem(value[0])" class="el-tag__close el-icon-close"></i>
            </div>
            <div class="flex-x open-data-item" v-show="value && value.length > 1">
              +{{value.length - 1}}
            </div>
          </template>
          <template v-else>
            <div v-for="item in value" :key="item.id" class="flex-x open-data-item">
              <div class="open-data-item-con">{{item.displayName}}</div> <i @click.stop="deleteItem(item)" class="el-tag__close el-icon-close"></i>
            </div>
          </template>
          <div class="form-user-placeholder" v-show="!value || !value.length">{{placeholder}}</div>
      </div>
      
    </template>
    <button type="button" class="btn-text form-user-clear" @click="clear" v-if="!isEmpty && !disabled">
      <i class="iconfont icon-fe-close"></i>
    </button>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import FormMixin from '@src/component/form/mixin/form';
import _ from 'lodash';

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'

export default {
  name: 'form-user',
  mixins: [FormMixin],
  props: {
    placeholder: {
      type: String,
      default: ''
    },
    /* 是否只显示 自己所在团队 人员  */
    seeAllOrg: {
      type: Boolean,
      default: false
    },
    value: [Object, Array],
    /* 是否是 多选 */
    multiple: {
      type: Boolean,
      default: false
    },
    /* 选人 配置项 */
    max: [String, Number],
    /* 是否显示离职人员 */
    showDeleteUser: {
      type: Boolean,
      default: false
    },
    /* 是否效验是不是主管 */
    isJudge: {
      type: String,
      default: ''
    },
    // 服务窗 控制左边树 【0组织架构】 【1服务商】 【''全部】 默认和之前逻辑一样
    typeServiceProvider: {
      type: Number | String,
      default: ''
    },
    // 开启此条件的前提必须保证value是数组且数组内是完整的User对象包含 displayName、id、staffId等
    canDelete:{
      type: Boolean,
      default: false
    },
    // 与canDelete组合使用 折叠标签
    collapseTags:{
      type: Boolean,
      default: false
    },
    // 传入$fast需要入参的参数
    selectOptions:{
      type:[Object, null],
      default:null
    },
    // 传入$fast需要调用的方法名
    selectFn:{
      type:String,
      default:''
    },
    /** 
     * @description 如果是服务商成员的话显示部门 tab
    */
    showTagIfSpUser: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    /** 
    * @description 多选
    * 1.multiple
    * 2.或 人员字段设置可多选
    */
    _multiple() {
      let { isMultiple } = this.field.setting || {};
      return this.multiple || isMultiple == 1;
    },
    displayName(){
      // 多选
      if(Array.isArray(this.value)) {
        return this.value.map(i => i.displayName || i.name).join(',');
      }
      
      let user = this.value || {};
      return user.displayName || user.name;
    },
    staffIds(){
      console.log('staffIds value:', this.value);
      if(Array.isArray(this.value)) {
        return this.value.map(i => i.staffId);
      }
      let user = this.value || {};
      if(user.staffId) return [user.staffId];
    },
    // 根据userId判断是否为空
    isEmpty(){
      // 多选
      if(Array.isArray(this.value)) {
        return this.value.length <= 0;
      }

      let value = this.value || {};
      return !value.userId;
    },
    /** 
    * @description 显示离职人员
    * 1.通过prop showDeleteUser
    * 2.或 人员字段设置可显示离职人员
    */
    seeDeleteUser() {
      let { showDeleteUser } = this.field.setting || {};
      return this.showDeleteUser || showDeleteUser == 1;
    },
    _max() {
      let _max = 1
      
      let { max } = this.field.setting || {};

      if(this._multiple) {
        _max = this.max || max
        _max = null == _max ? -1 : parseInt(_max)
      }
      return _max
    },
    selectOptionsValue(){
       return this.selectOptions || this.field?.setting?.selectOptions || {}
    },
    selectFnValue(){
      return this.selectFn || this.field?.setting?.selectFn || 'user'
    }
  },
  data() {
    return {
      isOpenData,
    }
  },
  methods: {
    choose(){
      // let max = 1;
      // if(this._multiple) max = null == this.max ? -1 : parseInt(this.max)
      let max = this._max
      let options = {
        title:  this.$t('common.placeholder.selectSomething', {0:this.field.displayName}),
        selectedUsers: this._multiple ? this.value : null,
        showDelete: this.seeDeleteUser,
        max,
        unique: false,
        top: true,
        typeServiceProvider: this.typeServiceProvider,
        isJudge: this.isJudge,
        mode: BaseSelectUserModeEnum.Filter,
        showTagIfSpUser: this.showTagIfSpUser,
        ...this.selectOptionsValue
      };
      let fnc = this.selectFnValue || 'user'
      return this.$fast.select.multi[fnc](options).then(result => {
        if(result.status == 0){
          let oldValue = null;
          let data = result.data || {};
          let users = data.users || [];
          let newValue = this._multiple ? users : users[0];

          this.$emit('update', {newValue, oldValue, field: this.field});
          this.$emit('input', newValue);

          this.$el.dispatchEvent(new CustomEvent('form.validate', {bubbles: true}));
        }
      })
        .catch(err => console.error(err))
    },
    clear(){
      let value = this._multiple ? [] : {};
      this.$emit('update', {newValue: value, field: this.field});
      this.$emit('input', value);
    },
    deleteItem(item){
      const {  staffId, userId } = item;
      let value = _.cloneDeep(this.value);
      
      if(this._multiple){
        let index = this.value.findIndex(v=>v.userId == userId || v.staffId == staffId)
        console.log(index, this.value, '*********')
        index > -1 && value.splice(index, 1) 
      }else{
        value = {}
      }
      this.$emit('update', {newValue: value, field: this.field});
      this.$emit('input', value);
    }
  },
}
</script>

<style lang="scss">
.form-user{
  width: 100%;
  position: relative;
  
  input{
    padding-right: 32px;
    width: 100%;
    cursor: pointer;
  }
  
  .open-data-input{
    padding-right: 32px;
    width: 100%;
    cursor: pointer;
    padding: 6px 32px 3px 10px;
    line-height: 24px;
    min-height: 32px;
    border: 1px solid #e0e1e2;
    border-radius: 4px;
    margin: 0;
    outline: none;
    color: #333 !important;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    .form-user-placeholder{
      @include text-ellipsis();
      width:90%;
      color: #B3B7C1;
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
    &:hover{
      border-color: $input-border-hover-color;
    }

    // copy于 el-tag下的close-icon样式
    .open-data-item{
      &:not(:first-child){
        margin-left:6px;
      }
      margin-right: 6px;
      margin-bottom:3px;
      color: #909399 !important;
      max-width: 100%;
      font-size: 12px;
      border-width: 1px;
      border-style: solid;
      border-radius: 4px;
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      height: 20px;
      padding: 0 5px;
      line-height: 19px;
      .open-data-item-con{
        overflow: hidden;
        text-overflow: ellipsis;
        word-break:keep-all;
        flex:1;
      }
      .el-icon-close{
        border-radius: 50%;
        text-align: center;
        position: relative;
        cursor: pointer;
        font-size: 12px;
        height: 16px;
        width: 16px;
        line-height: 16px;
        vertical-align: middle;
        background-color: #c0c4cc;
        margin-left: 8px;
        -ms-transform: scale(0.7);
        transform: scale(0.7);
        &:hover{
          color: #FFFFFF;
          background-color: #909399;
        }
      }
    }
  }

  &:hover .form-user-clear{
    display: block;
  }
}

.form-user-clear{
  position: absolute;
  top: 50%;
  right: 0;
  width: 32px;
  height: 32px;
  transform: translateY(-16px);
  padding: 0;
  margin: 0;
  color: #c0c4cc;
  
  display: none;
  
  i{
    font-size: 14px;
  }
  
  &:hover{
    color: #ed3f14;
  }
}
</style>
